package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.FileBean;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.photo.entity.PhotoItem;
import com.sczmgk.hotline_pzh.popup.PupDialog;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.BitmapUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.FileUtil;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.PictureUtil;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.view.PersonalInfoItemView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/5 0005.
 */
public class PersonalInfoActivity extends BaseActivity {

    private static final int REFRESH_LIST = 101;

    private UserDaoImpl userDao;

    /*头像条目的控件*/
    private LinearLayout mLayoutPhoto;

    /*头像*/
    private ImageView mIvImage;

    /*姓名,电话,证件号,邮箱的条目控件*/
    private PersonalInfoItemView mPivName;
    private PersonalInfoItemView mPivPhone;
    private PersonalInfoItemView mPivCardID;
    private PersonalInfoItemView mPivEmail;

    /*地址的文本*/
    private TextView mTvAddress;

    /**
     * 图片的集合
     */
    private PhotoItem picBean = new PhotoItem();


    private BitmapDisplayConfig displayConfig;
    private LinearLayout mLayoutAddress;
    private Uri mNewPhotoUri;
    private User user;
    private int userid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);

        userDao = UserDaoImpl.getIntance(PersonalInfoActivity.this);

        setHeader();

        initView();

        setListener();

    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.personal_info);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //头像条目控件
        mLayoutPhoto = (LinearLayout) findViewById(R.id.ll_personal_info_photo);
        //头像控件
        mIvImage = (ImageView) findViewById(R.id.iv_personal_info_photo_image);

        //姓名,电话,证件号,邮箱
        mPivName = (PersonalInfoItemView) findViewById(R.id.piv_info_name);
        mPivPhone = (PersonalInfoItemView) findViewById(R.id.piv_info_phone);
        mPivCardID = (PersonalInfoItemView) findViewById(R.id.piv_info_card_id);
        mPivEmail = (PersonalInfoItemView) findViewById(R.id.piv_info_email);

        //地址的条目控件
        mLayoutAddress = (LinearLayout) findViewById(R.id.ll_personal_info_address);
        //地址的文本
        mTvAddress = (TextView) findViewById(R.id.tv_personal_info_address);

        //刷新用户信息
        refreshUserInfo();
    }

    /**
     * 更新用户信息
     */
    private void refreshUserInfo() {
        user = userDao.findByQuery(CacheUtils.getIntData(PersonalInfoActivity.this, Constants.LOGIN_UID, 0));
        Bitmap bitmap = BitmapUtils.getBitmap(user.imageLocalPath, 200, 200);
        if (bitmap != null) {
            mIvImage.setImageBitmap(bitmap);
        } else {
            mIvImage.setImageResource(R.drawable.personal_center_photo);
        }
        mTvAddress.setText(user.address);
        mPivCardID.setText(user.idcard);
        mPivName.setText(user.consumersname);
        mPivPhone.setText(user.phone);
        mPivEmail.setText(user.mailbox);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshUserInfo();
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //头像条目的点击
        mLayoutPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftKeyboard(PersonalInfoActivity.this);
                showPup(PupDialog.ID_PHOTO, new PhotoPupEvent());
            }
        });

        //地址条目的点击
        mLayoutAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, ChangeAddressActivity.class);
                intent.putExtra(ResultParam.ADDRESS, mTvAddress.getText());
                intent.putExtra(ResultParam.FLAG, Constants.PERSONAL_ADDRESS_INFO);
                startActivityForResult(intent, Param.REQUEST_CHANGE_ADDRESS);
            }
        });

        //手机条目的点击
        mPivPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, PhoneNumberActivity.class);
                startActivityForResult(intent, Param.REQUEST_CHANGE_ADDRESS);
            }
        });

        //邮箱的点击
        mPivEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, ChangeAddressActivity.class);
                intent.putExtra(ResultParam.EMAIL, mPivEmail.getTextInfo());
                intent.putExtra(ResultParam.FLAG, Constants.PERSONAL_EMAIL_INFO);
                startActivityForResult(intent, Param.REQUEST_CHANGE_ADDRESS);
            }
        });

    }

    public static class Param {
        /**
         * intent 传递联系人是否上传图像的key
         */
        public static final String INTENT_KEY_ISLoadLOGINUSERPHOTO = "loadloginuserphonto";
        public static final String INTENT_KEY_UPDAEINFO = "updateinfo";
        public static final int RESULT_CODE_UPDATE_NICKNAME = 0;
        public static final int RESULT_CODE_UPDATE_AREA = 2;
        public static final int PHOTOTAKEN_REQUEST_SIGN = 1010;

        /**
         * 系统相册返回
         */
        public static final int TAKE_PICTURE_SIGN = 1030;
        /**
         * 自定义相册返回
         */
        public static final int REQUEST_CODE_SELECT_PHOTO = 1040;
        /**
         * 图像裁切后的回调
         */
        public static final int REQUEST_PHOTO_RESULT = 204;

        /**
         * 更改地址后的请求码
         */
        public static final int REQUEST_CHANGE_ADDRESS = 100;
        /**
         * 更改地址后的请求码
         */
        public static final int RESULT_ADDRESS = 1001;

    }

    /**
     * 本类返回的详细信息
     *
     * @author luochun
     */
    public static class ResultParam {
        /**
         * 当前用户选择的相片
         */
        public static final String SELECT_PHOTO_LIST = "photo_list";

        /**
         * 用户输入的地址
         */
        private static final String ADDRESS_TEXT = "address";

        public static final String ADDRESS = "address_info";
        public static final String EMAIL = "email_info";

        /**
         * 用户输入的手机号
         */
        public static final String PHONE = "phone";

        private static final String PHONE_TEXT = "phone_info";
        public static final String FLAG = "flag";
    }


    /**
     * 选择图片pop的点击事件
     *
     * @author
     */
    class PhotoPupEvent implements PupDialog.PupEvent {

        @Override
        public void itemOnClick(PupDialog pupid, View item, int position) {
            switch (position) {
                case 0:
                    takePhoto();
                    break;
                case 1:
                    // 点击了选择图片的处理
                    startActivityForResult(new Intent(Intent.ACTION_PICK, null).setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"), Param.TAKE_PICTURE_SIGN);
                    break;

                default:
                    break;

            }
            pupid.dismiss();
        }

    }

    /***
     * 拍照
     */
    private void takePhoto() {
        // 点击了照相的处理
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String mPhotoPath = FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH + File.separator + "captureTemp.png";
        MyLog.i(TAG, "点击了照相     mPhotoPath:  " + mPhotoPath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPhotoPath)));//图片输出的URL
        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, Configuration.ORIENTATION_PORTRAIT);
        startActivityForResult(intent, Param.PHOTOTAKEN_REQUEST_SIGN);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Param.PHOTOTAKEN_REQUEST_SIGN: // 拍照
                    // 拍照返回
                    String mPhotoPath = FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH + File.separator + "captureTemp.png";
                    MyLog.i(TAG, "拍照返回了..... mPhotoPath:  " + mPhotoPath);
                    File file = new File(mPhotoPath);
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                        if (fis == null)
                            return;
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        return;
                    }
                    if (file.isFile()) {
                        PictureUtil.startPhotoZoomClipLimit(Uri.fromFile(file), mHandler, this, Param.REQUEST_PHOTO_RESULT, 1, 1, true);
                    }
                    break;

                case Param.REQUEST_CHANGE_ADDRESS:

                    user = UserDaoImpl.getIntance(PersonalInfoActivity.this).findByQuery(userid);
                    if (user != null) {
                        refreshUserInfo();
                    }

                    break;
                case Param.TAKE_PICTURE_SIGN: // 选择相册
                    // 选择相册返回
                    MyLog.i(TAG, "选择相册返回了.....");
                    if (intent == null) {
                        return;
                    }
                    PictureUtil.startPhotoZoomClipLimit(intent.getData(), mHandler, this, Param.REQUEST_PHOTO_RESULT, 1, 1, false);
                    break;
                case Param.REQUEST_PHOTO_RESULT://
                    MyLog.d(TAG, "裁剪图片返回了---------------------");
                    // 防止数据为空
                    if (intent == null)
                        return;
                    if (PictureUtil.getClipTempFile() != null) {
                        compressPic(PictureUtil.getClipTempFile());
                    }
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 压缩图片
     *
     * @param imagePath
     */
    private void compressPic(final String imagePath) {

        final String uploadPicTempFilePath = FileUtil.getUploadPicTempFilePath();
        MyLog.d(TAG, "原图片路径 :　 " + imagePath + "临时文件路径　：　" + uploadPicTempFilePath);

        //1.将图片压缩存入临时文件
        BitmapUtils.compressBitmap(uploadPicTempFilePath, imagePath, 400, 400, new BitmapUtils.CompressBitmapCallback() {

            @Override
            public void compress(final String tempPath) {
                MyLog.d(TAG, "另存压缩临时图片的路径是：" + tempPath);
                uploadPhoto(imagePath, tempPath);
            }
        });
    }

    /**
     * 上传图片到服务器
     *
     * @param filePath 要上传的图片路径
     * @return true 上传成功, false 上传失败
     */
    private void uploadPhoto(final String filePath, final String tempPath) {

        Map<String, Object> uploadMaps = new HashMap<String, Object>();
        String desc = "desc";
        int module = Constants.PIC_MODULE_USER;
        String relateid = "1";
        String remark = "remark";
        String size = "100*100";
        int time = 100;
        uploadMaps.put("desc", desc);
        uploadMaps.put("size", size);
        uploadMaps.put("relateid", relateid);
        uploadMaps.put("module", module);
        uploadMaps.put("time", time);
        uploadMaps.put("remark", remark);
        MyLog.e(TAG, "filePath: " + filePath);
        MyHttp.requestByUploadPic(Constants.BASE_URL + Constants.POST_UPLOD_FILE_URL, filePath, uploadMaps, MyHttp.UPLOAD_FILE, PersonalInfoActivity.this,
                false, null, new SimplePaserJsonCallback() {

                    @Override
                    public void onVerifySuccess(String dataRaw, boolean isCache) {
                        paserDataJson(dataRaw);//上传成功

                        boolean deleteDirectory = FileUtil.delete(tempPath);
                        if (deleteDirectory) {
                            MyLog.d(TAG, "删除临时图片成功 -------------" + tempPath);
                        } else {
                            MyLog.e(TAG, "删除临时图片失败----------路径是：" + tempPath);
                        }
                    }

                    @Override
                    public void onVerifyIsNull() {
                    }

                });
    }

    /**
     * 过时的根据URi取得文件的绝对路径
     *
     * @return
     */
    private String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};

        Cursor cursor = managedQuery(uri,
                proj,       // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);                 // Order-by clause (ascending by name)

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }

    /**
     * @param dataRaw
     */
    private void paserDataJson(String dataRaw) {
        if (Tools.isEmpty(dataRaw)) {
            MyToast.showDebug(PersonalInfoActivity.this, "json  error!");
            return;
        }

        loadingDialog = DialogFactory.getLoadingDialog(PersonalInfoActivity.this) ;
        DialogFactory.showDialog(loadingDialog);

        MyLog.d(TAG, "-取得存取图片返回的 JSON :    " + dataRaw);
        Gson gson = new Gson();
        FileBean fileBean = gson.fromJson(dataRaw, FileBean.class);
        List<FileBean.FileName> datalist = fileBean.datalist;
        String headPath = "";
        for (int i = 0; i < datalist.size(); i++) {
            headPath = datalist.get(i).filename;
        }

        final String iconPath = headPath;
        //////////////////////////////////////////////////////
        // 1.上传服务器
        // 2.修改数据库
        commit(iconPath);
    }


    /**
     * 提交数据sdfsfd
     *
     * @param iconPath
     */
    private void commit(final String iconPath) {

        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", user.userid);
        maps.put("headurl", iconPath);
        maps.put("address", user.address);
        maps.put("sex", user.sex);
        maps.put("nickname", user.nickname);
        maps.put("phone", user.phone);
        maps.put("easemobsaccount", user.easemobsaccount);
        maps.put("easemobspassword", user.easemobspassword);
        maps.put("mailbox", user.mailbox);

        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.POST_UPDATE_USERINFO, maps, MyHttp.POST, PersonalInfoActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                DialogFactory.dismissLoadingDialog(loadingDialog);

                String path = FileUtil.getUserCaptureCacheFilePath(user.userid + "");

                //提交成功后将地址更新至数据库
                FileUtil.copyFile(new File(PictureUtil.getClipTempFile()), new File(path));
                //2.存入本地图片路径
                user.imageLocalPath = (path);
                user.headurl = iconPath;
                userDao.updata(user);

                //3.删除临时图片
                if (FileUtil.delete(PictureUtil.getClipTempFile())) {
                    MyLog.d(TAG, "临时图片删除成功!");
                }
                //刷新界面
                refreshUserInfo();
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(PersonalInfoActivity.this, mError.msg);
            }
        }, new HttpFailCallback() {
            @Override
            public void onServiceErrorCallback() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(PersonalInfoActivity.this, "头像更新失败,请稍后再试");
            }
        });

    }


}
